package com.example.springboot.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.controller.dto.UserDto;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ShanYuqing
 * @Version: v1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public List<User> findAll() {
        return userService.list();
    }

    @PostMapping("/add")
    public Result save(@RequestBody User user) {
        return Result.success(userService.insert(user));
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDto userdto) {
        String username = userdto.getUsername();
        String password = userdto.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.register(userdto));
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDto userdto) {
        String username = userdto.getUsername();
        String password = userdto.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDto dto = userService.login(userdto);
        return Result.success(dto);
    }

    @DeleteMapping("/{id}")
    public Result deleteByid(@PathVariable Integer id) {
        return Result.success( userService.removeById(id));
    }


    @GetMapping("/username/{username}")
    public Result findone(@PathVariable String username) {
        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper)) ;
    }
    //分页查询
    //@RequestParam接收 ？pageNum=1&pageSize=10
    //limit的第一个参数 = （pagenum -1）*pagesize
//    @GetMapping("/page")
//    public Map<String,Object>  findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
//      @RequestParam String username ){
//        pageNum = (pageNum-1) * pageSize;
//        username = '%'+username+'%';
//        Integer total = userMapper.selectTotal(username);
//        List<User> data = userMapper.selectPage(pageNum, pageSize,username);
//        Map<String,Object> res = new HashMap<>();
//        res.put("data",data);
//        res.put("total",total);
//        return res;
//    }
//分页查询-mybatis-plus的方法
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String username, @RequestParam(defaultValue = "") String address) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }
        if (!"".equals(address)) {
            queryWrapper.like("address", address);
        }
        return Result.success(userService.page(page, queryWrapper));
    }

    @PostMapping("/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {

        return Result.success(userService.removeByIds(ids)) ;
    }

    /**
     *导出excel
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        //从数据库查询出所有数据
        List<User> list = userService.list();
        //通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatar", "头像");
        writer.write(list,true);
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName +".xlsx");
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        writer.close();

    }
    /**
     *
     */
    @PostMapping("/import")
    public void imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<User> list = reader.readAll(User.class);
        System.out.println(list);
    }

}
